package com.itheima.demo7;

import java.io.*;
import java.net.Socket;

public class ClientDemo4 {
    public static void main(String[] args) throws IOException {
        //TCP协议，发送数据

        //1.创建Socket对象
        //细节：在创建对象的同时会连接到服务器，如果连接不上会报错
        Socket sc = new Socket("127.0.0.1",10086);

        //2.从连接通道中获取输出流写出数据
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(sc.getOutputStream());
        //写出数据(通过字节数组的形式)
        byte[] bytes = new byte[1024];
        int len ;
        while ((len = bis.read(bytes)) != -1){
            bos.write(bytes,0,len);
        }

        //3.读取回写数据
        //创建字符缓冲流进行数据读取
        BufferedReader br = new BufferedReader(new InputStreamReader(sc.getInputStream()));
        int b;

        //细节：read方法会一直从通道中读取数据，需要有一个结束标记才会停止运行
        while ((b = br.read()) != -1) {
            System.out.print((char) b);
        }

        //释放资源
        bis.close();
        sc.close();

    }
}
